from components.ERROR_MAP import ERROR_CODE
import pandas as pd

def analyze_add_workflow(df):
    """重建添加人脸工作流程"""
    
    # 添加错误描述
    df['error_desc'] = df['ret_code'].map(ERROR_CODE).fillna('未找到错误码')
    
    # 重建完整工作流程
    workflows = []
    current_flow = {}
    
    for _, row in df.sort_values('timestamp').iterrows():
        # 新流程开始 (act=1 或 act=255)
        if row['act_phase'] == 1 or not current_flow:
            if current_flow:  # 保存上一个流程
                workflows.append(current_flow)

            current_flow = {
                'steps': {}
            }
        
        # 记录步骤信息
        step_key = f"step_{row['act_phase']}"
        current_flow['steps'][step_key] = {
            'timestamp': row['timestamp'],
            'ret_code': row['ret_code'],
            'error_desc': row['error_desc'],
            'status': True if row['ret_code'] in ('0x00', '0x0') else False
        }
        
        # 流程结束标记 (act=255)
        if row['act_phase'] == 255:
            workflows.append(current_flow)
            current_flow = {}
    
    # 转换为DataFrame
    workflow_df = pd.DataFrame(workflows)
    return workflow_df